//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package user_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type UserAppDbItem struct {
	UserAppId string `bson:"_id"`
	UserId    string `bson:"userId"`
	AppId     string `bson:"appId"`
	TimeStamp int64  `bson:"timeStamp"`
}

type _UserAppDao struct {
	mc *mongo.Collection
}

func newUserAppDao(db *mongo.Database) (*_UserAppDao, error) {
	mc := db.Collection(db_ns.DB_NS_USER + "app_v2")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"userId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_UserAppDao{mc: mc}, nil
}

func (db *_UserAppDao) Insert(ctx context.Context, dbItem *UserAppDbItem) error {
	dbItem.UserAppId = db.genUserAppId(dbItem.UserId, dbItem.AppId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_UserAppDao) genUserAppId(userId, appId string) string {
	return fmt.Sprintf("%s:%s", userId, appId)
}

func (db *_UserAppDao) Exist(ctx context.Context, userId, appId string) (bool, error) {
	userAppId := db.genUserAppId(userId, appId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": userAppId})
	return (count > 0), err
}

func (db *_UserAppDao) Get(ctx context.Context, userId, appId string) (*UserAppDbItem, error) {
	userAppId := db.genUserAppId(userId, appId)
	retItem := &UserAppDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": userAppId}).Decode(retItem)
	return retItem, err
}

func (db *_UserAppDao) Remove(ctx context.Context, userId, appId string) error {
	userAppId := db.genUserAppId(userId, appId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": userAppId})
	return err
}

func (db *_UserAppDao) UpdateTimeStamp(ctx context.Context, userId, appId string, timeStamp int64) error {
	userAppId := db.genUserAppId(userId, appId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": userAppId}, bson.M{
		"$set": bson.M{
			"timeStamp": timeStamp,
		},
	})
	return err
}

func (db *_UserAppDao) List(ctx context.Context, userId string) ([]*UserAppDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"userId": userId}, options.Find().SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*UserAppDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
